import { baseParaTagName } from '../config';
import { initLangSelect } from './initLangSelect';
import { setRoot as kdhSetRoot, keydownHandler } from '../handlers/keydown';
import { setRoot as mhSetRoot, messageHandler } from '../handlers/message';
import { setRoot as phSetRoot, pasteHandler } from '../handlers/paste';
import { setRoot as cpSetRoot, copyHandler } from '../handlers/copy';
import { setRoot as rcSetRoot, record } from '../revoke/record';
import hljs from '../highlight/index';

function init(root) {

  // clear
  root.innerHTML = '';

  // RTF
  const RTF = document.createElement('DIV');
  RTF.id = 'RTF';
  RTF.contentEditable = true;
  RTF.appendChild(document.createElement(baseParaTagName));
  root.appendChild(RTF);

  // langSelect
  const langSelect =  document.createElement('DIV');
  langSelect.id = 'langSelect';
  root.appendChild(langSelect);

  initLangSelect(langSelect, (lang, codeBlock) => {
    codeBlock.dataset.lang = lang;
  
    for(let i = 0; i < codeBlock.children.length; i++) {
      let child = codeBlock.children.item(i);
      let html = hljs.highlight(child.innerText, {
        language: codeBlock.dataset.lang
      }).value;
      child.innerHTML = html;
    }
  });
  
  kdhSetRoot(RTF);
  mhSetRoot(RTF);
  phSetRoot(RTF);
  cpSetRoot(RTF);
  rcSetRoot(RTF);
  
  document.addEventListener('keydown', keydownHandler);
  
  document.addEventListener('paste', pasteHandler);
  
  window.addEventListener('message', messageHandler);

  document.addEventListener('copy', copyHandler);
}

export default init;